//
//  WCAddToProjectSheetController.m
//  WabbitCode
//
//  Created by William Towe on 1/28/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCAddToProjectSheetController.h"
#import "WCProject.h"
#import "NSTreeNode+WCExtensions.h"
#import "WCProjectGroup.h"
#import "WCAppController.h"
#import "WCMacros.h"
#import "WCGroup.h"
#import "NSIndexPath+WCExtensions.h"
#import "NSTreeController+WCExtensions.h"
#import "NSDictionary+WCExtensions.h"
#import "EncodingManager.h"
#import "WCTextFile.h"


NSString *kWCAddToProjectFilePathsKey = @"kWCAddToProjectFilePathsKey";
NSString *kWCAddToProjectProjectKey = @"kWCAddToProjectProjectKey";
NSString *kWCAddToProjectGroupItemKey = @"kWCAddToProjectGroupItemKey";
NSString *kWCAddToProjectGroupInsertionIndexKey = @"kWCAddToProjectGroupInsertionIndexKey";

@interface WCAddToProjectSheetController (Private)
- (NSSet *)currentProjectFilePaths;
- (void)setCurrentProjectFilePaths:(NSSet *)value;
@end

@implementation WCAddToProjectSheetController
#pragma mark *** Subclass Overrides ***
- (id)init {
	return [self initWithWindowNibName:@"WCAddToProjectSheet"];
}

- (void)dealloc {
	[_currentProjectFilePaths release];
	[super dealloc];
}

- (void)windowDidLoad {
	[super windowDidLoad];
	
	[_encodingTypeButton setEncoding:NSUserDefaultsUnsignedIntegerForKey(kWCPrefsAddToProjectTextEncodingKey) defaultEntry:YES];
	[_checkboxButton setState:NSUserDefaultsBoolForKey(kWCPrefsAddToProjectCopyFilesKey)];
	[_openFilesAfterAddingButton setState:NSUserDefaultsBoolForKey(kWCPrefsAddToProjectOpenFilesAfterAddKey)];
}
#pragma mark NSSavePanel Delegate
- (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename {
	return ([[self currentProjectFilePaths] containsObject:filename])?NO:YES;
}
#pragma mark *** Public Methods ***
+ (void)presentAddToProjectSheetForProject:(WCProject *)project; {
	WCAddToProjectSheetController *controller = [[[self class] alloc] init];
	
	[controller setCurrentProjectFilePaths:[[project projectGroup] projectFilePaths]];
	
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	
	[panel setAllowsMultipleSelection:YES];
	[panel setCanChooseDirectories:YES];
	[panel setPrompt:NSLocalizedString(@"Add",@"Add")];
	[panel setDelegate:controller];
	
	[panel beginSheetForDirectory:nil file:nil modalForWindow:[project projectWindow] modalDelegate:controller didEndSelector:@selector(_openPanelDidEnd:code:info:) contextInfo:(void *)project];
}

+ (void)presentAddToProjectSheetWithInfoDictionary:(NSDictionary *)dict; {
	WCAddToProjectSheetController *controller = [[[self class] alloc] init];
	
	[NSApp beginSheet:[controller window] modalForWindow:[[dict objectForKey:kWCAddToProjectProjectKey] projectWindow] modalDelegate:controller didEndSelector:@selector(_addToProjectSheetDidEnd:code:info:) contextInfo:(void *)[dict retain]];
}

#pragma mark *** Private Methods ***
#pragma mark Callbacks
- (void)_openPanelDidEnd:(NSOpenPanel *)panel code:(NSInteger)code info:(void *)info {
	[self autorelease];
	[panel close];
	if (code != NSOKButton)
		return;
	
	[self retain];
	
	[NSApp beginSheet:[self window] modalForWindow:[(WCProject *)info projectWindow] modalDelegate:self didEndSelector:@selector(_sheetDidEnd:code:info:) contextInfo:(void *)[[NSDictionary alloc] initWithObjectsAndKeys:(WCProject *)info, kWCAddToProjectProjectKey, [panel filenames], kWCAddToProjectFilePathsKey, nil]];
}

- (void)_sheetDidEnd:(NSWindow *)sheet code:(NSInteger)code info:(void *)info {
	[self autorelease];
	[(id)info autorelease];
	if (code != NSOKButton)
		return;
	
	NSSetUserDefaultsUnsignedIntegerForKey([_encodingTypeButton selectedTag], kWCPrefsAddToProjectTextEncodingKey);
	NSSetUserDefaultsBoolForKey([_checkboxButton state], kWCPrefsAddToProjectCopyFilesKey);
	NSSetUserDefaultsBoolForKey([_openFilesAfterAddingButton state], kWCPrefsAddToProjectOpenFilesAfterAddKey);
	
	WCProject *project = [(NSDictionary *)info objectForKey:kWCAddToProjectProjectKey];
	
	NSTreeNode *node = [project selectedFileNode];
	NSUInteger index = ([node isLeaf])?[[node indexPath] lastIndex]:0;
	
	if ([node isLeaf])
		node = [node parentNode];
	
	NSArray *representedObjects = [[node representedObject] insertFilePaths:[(NSDictionary *)info objectForKey:kWCAddToProjectFilePathsKey] atIndex:index copyFiles:[_checkboxButton state] usingEncoding:([_encodingTypeButton selectedTag] == NoStringEncoding)?kWCDefaultFileEncoding:[_encodingTypeButton selectedTag]];
	
	[[project projectTreeController] selectRepresentedObjects:representedObjects];
	[project setShouldRecacheTextFiles:YES];
	[project setShouldRecacheProjectSymbols:YES];
	[project setShouldRecacheProjectSymbolsArray:YES];
	[project updateAllTabViewContexts];
	
	if ([_openFilesAfterAddingButton state]) {
		for (id file in representedObjects) {
			if ([file isKindOfClass:[WCTextFile class]]) {
				[project addTabViewItemForTextFile:file inTabViewContext:project];
			}
		}
	}
}

- (void)_addToProjectSheetDidEnd:(NSWindow *)sheet code:(NSInteger)code info:(void *)info {
	[self autorelease];
	[(id)info autorelease];
	if (code != NSOKButton)
		return;
	
	NSSetUserDefaultsUnsignedIntegerForKey([_encodingTypeButton selectedTag], kWCPrefsAddToProjectTextEncodingKey);
	NSSetUserDefaultsBoolForKey([_checkboxButton state], kWCPrefsAddToProjectCopyFilesKey);
	NSSetUserDefaultsBoolForKey([_openFilesAfterAddingButton state], kWCPrefsAddToProjectOpenFilesAfterAddKey);
	
	WCProject *project = [(NSDictionary *)info objectForKey:kWCAddToProjectProjectKey];
	
	NSTreeNode *node = [(NSDictionary *)info objectForKey:kWCAddToProjectGroupItemKey];
	NSUInteger index = [(NSDictionary *)info integerForKey:kWCAddToProjectGroupInsertionIndexKey];
	
	NSArray *representedObjects = [[node representedObject] insertFilePaths:[(NSDictionary *)info objectForKey:kWCAddToProjectFilePathsKey] atIndex:index copyFiles:[_checkboxButton state] usingEncoding:([_encodingTypeButton selectedTag] == NoStringEncoding)?kWCDefaultFileEncoding:[_encodingTypeButton selectedTag]];
	
	[[project projectTreeController] selectRepresentedObjects:representedObjects];
	[project setShouldRecacheTextFiles:YES];
	[project setShouldRecacheProjectSymbols:YES];
	[project setShouldRecacheProjectSymbolsArray:YES];
	[project updateAllTabViewContexts];
	
	if ([_openFilesAfterAddingButton state]) {
		for (id file in representedObjects) {
			if ([file isKindOfClass:[WCTextFile class]]) {
				[project addTabViewItemForTextFile:file inTabViewContext:project];
			}
		}
	}
}

- (NSSet *)currentProjectFilePaths; {
	return _currentProjectFilePaths;
}
- (void)setCurrentProjectFilePaths:(NSSet *)value; {
	[_currentProjectFilePaths release];
	_currentProjectFilePaths = [value retain];
}


@end
